package stack_quene.stack.quene.impl;

import stack_quene.stack.quene.Queue;

public class LoopQueue implements Queue {
    private int[] data;
    //有效元素个数
    private int size;
    private int front;
    private int tail;

    public LoopQueue(int k) {
        data=new int[k+1];
    }

    @Override
    public void offer(int value) {
        //判断循环队列是否已满
        if(isFull()){
            System.out.println("queue is full");
            return;
        }
        data[tail]=value;
        tail=(tail+1)%data.length;
        size++;

    }

    @Override
    public int poll() {
        //判断循环队列是否为空
        if(isEmpty()){
            System.out.println("queue is empty");
            return -1;
        }
        int value=data[front];
        front=(front+1)%data.length;
        size--;
        return value;
    }

    @Override
    public int peek() {
        if (isEmpty()){
            System.out.println("queue is empty");
        }
        return data[front];
    }

    //如何查看队尾元素
    public int getTail(){
        if (isEmpty()){
            System.out.println("queue is empty");
        }
        int index=tail==0?data.length-1:tail-1;
        return data[index];
    }

    @Override
    public boolean isEmpty() {
        if(front==tail){
            return true;
        }
        return false;
    }

    public boolean isFull(){
        if((tail+1)%data.length==front){
            return true;
        }
        return false;
    }
    public int  getSize(){
        return size;
    }

    //遍历数组
    public String toString(){
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("front [");
        for (int i = front; i !=tail ;) {
            stringBuilder.append(data[i]);
            if(i!=tail-1){
                stringBuilder.append(",");
            }
            i=(i+1)%data.length;
        }
        stringBuilder.append("] tail");
        return stringBuilder.toString();
    }


}
